﻿Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text.RegularExpressions
Imports System.IO

Namespace DotNetNuke.Modules.ActiveForums.Controls
    <DefaultProperty("Text"), ToolboxData("<{0}:ForumView runat=server></{0}:ForumView>")> _
    Public Class ForumView
        Inherits ForumBase
        Private dtForums As DataTable = Nothing
        Private _SubsOnly As Boolean = False
        Private ForumURL As String = String.Empty
        Private ForumPageTitle As String = String.Empty
        Private _DisplayTemplate As String = ""
        Private _currentUserId As Integer = -1
        Public Property SubsOnly() As Boolean
            Get
                Return _SubsOnly
            End Get
            Set(ByVal value As Boolean)
                _SubsOnly = value
            End Set
        End Property
        Public Property DisplayTemplate() As String
            Get
                Return _DisplayTemplate
            End Get
            Set(ByVal value As String)
                _DisplayTemplate = value
            End Set
        End Property
        Public Property ForumTable() As DataTable
            Get
                Return dtForums
            End Get
            Set(ByVal value As DataTable)
                dtForums = value
            End Set
        End Property
        Public Property CurrentUserId() As Integer
            Get
                Return _currentUserId
            End Get
            Set(ByVal value As Integer)
                _currentUserId = value
            End Set
        End Property
        Protected WithEvents ctlForumJump As New DotNetNuke.Modules.ActiveForums.af_quickjump
#Region "Event Handlers"

        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            Me.AppRelativeVirtualPath = "~/"

            Try

                If CurrentUserId = -1 Then
                    CurrentUserId = UserId
                End If
                Dim sOutput As String = String.Empty
                Try
                    Dim defaultTemplateId As Integer = MainSettings.ForumTemplateID
                    If DefaultForumViewTemplateId >= 0 Then
                        defaultTemplateId = DefaultForumViewTemplateId
                    End If
                    sOutput = BuildForumView(defaultTemplateId, CurrentUserId, Page.ResolveUrl("~/DesktopModules/ActiveForums/themes/" & MainSettings.Theme & "/"))
                Catch ex As Exception
                    'sOutput = ex.Message
                    'DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, ex)
                End Try

                If Not sOutput = String.Empty Then
                    Try
                        If sOutput.Contains("[TOOLBAR") Then
                            Dim lit As New LiteralControl
                            Dim sToolbar As Object = Nothing 'DataCache.CacheRetrieve("aftb" & ModuleId)
                            If sToolbar Is Nothing Then
                                sToolbar = Utilities.GetFileContent(SettingKeys.TemplatePath & "ToolBar.txt")
                                DataCache.CacheStore("aftb" & ModuleId, sToolbar)
                            End If
                            sToolbar = Utilities.ParseToolBar(sToolbar.ToString, TabId, ModuleId, UserId, CurrentUserType)
                            lit.Text = sToolbar.ToString
                            sOutput = sOutput.Replace("[TOOLBAR]", sToolbar.ToString)
                        End If
                        Dim tmpCtl As Control = Nothing
                        Try

                            tmpCtl = Me.ParseControl(sOutput)

                        Catch ex As Exception

                        End Try
                        If Not tmpCtl Is Nothing Then
                            Try
                                Me.Controls.Add(tmpCtl)
                                LinkControls(Me.Controls)
                                If Not SubsOnly Then
                                    Dim plh As PlaceHolder = CType(tmpCtl.FindControl("plhQuickJump"), PlaceHolder)
                                    If Not plh Is Nothing Then
                                        ctlForumJump = New af_quickjump
                                        ctlForumJump.MOID = ModuleId
                                        ctlForumJump.dtForums = ForumTable
                                        ctlForumJump.ModuleId = ModuleId
                                        plh.Controls.Add(ctlForumJump)
                                    End If
                                    plh = CType(tmpCtl.FindControl("plhUsersOnline"), PlaceHolder)
                                    If Not plh Is Nothing Then
                                        Dim ctlWhosOnline As New ForumBase
                                        ctlWhosOnline = CType(LoadControl("~/Desktopmodules/ActiveForums/controls/af_usersonline.ascx"), ForumBase)
                                        ctlWhosOnline.ModuleConfiguration = Me.ModuleConfiguration
                                        plh.Controls.Add(ctlWhosOnline)
                                    End If
                                End If

                            Catch ex As Exception

                            End Try

                        End If

                    Catch ex As Exception
                        DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, ex)

                    End Try
                End If




            Catch ex As Exception
                DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, ex)
            End Try

        End Sub

#End Region
#Region "Public Methods"
        Public Function BuildForumView(ByVal ForumTemplateId As Integer, ByVal CurrentUserId As Integer, ByVal ThemePath As String) As String
            Try
                Dim MainSettings As SettingsInfo = DataCache.MainSettings(ModuleId)
                Dim sOutput As String = String.Empty
                Dim sTemplate As String = String.Empty
                Dim TemplateCache As Integer = MainSettings.TemplateCache
                If UseTemplatePath And Not TemplatePath = String.Empty Then
                    DisplayTemplate = Utilities.GetFileContent(TemplatePath & "ForumView.htm")
                    DisplayTemplate = Utilities.ParseSpacer(DisplayTemplate)
                ElseIf DisplayTemplate = String.Empty Then
                    DisplayTemplate = Utilities.GetFileContent(Server.MapPath(ThemePath) & "templates/ForumView.ascx")
                    DisplayTemplate = Utilities.ParseSpacer(DisplayTemplate)
                End If

                If DisplayTemplate = String.Empty Then
                    sTemplate = DataCache.GetCachedTemplate(TemplateCache, ModuleId, "ForumView", ForumTemplateId)
                Else
                    sTemplate = DisplayTemplate
                End If
                Try
                    sTemplate = ParseControls(sTemplate)
                Catch ex As Exception
                    DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, ex)
                    sTemplate = ex.Message 'ParseControls(sTemplate)
                End Try
                If sTemplate.Contains("[NOTOOLBAR]") Then
                    If HttpContext.Current.Items.Contains("ShowToolbar") Then
                        HttpContext.Current.Items("ShowToolbar") = False
                    Else
                        HttpContext.Current.Items.Add("ShowToolbar", False)
                    End If
                    sTemplate = sTemplate.Replace("[NOTOOLBAR]", String.Empty)
                End If
                If sTemplate.Contains("[FORUMS]") Then
                    Dim sGroupSection As String = String.Empty
                    Dim sGroupSectionTemp As String = TemplateUtils.GetTemplateSection(sTemplate, "[GROUPSECTION]", "[/GROUPSECTION]")
                    Dim sGroup As String = TemplateUtils.GetTemplateSection(sTemplate, "[GROUP]", "[/GROUP]")
                    Dim sForums As String = String.Empty
                    Dim sForumTemp As String = TemplateUtils.GetTemplateSection(sTemplate, "[FORUMS]", "[/FORUMS]")
                    Dim tmpGroup As String = String.Empty
                    'Dim reader As IDataReader = Nothing
                    If ForumTable Is Nothing Then
                        Dim ds As New DataSet
                        dtForums = New DataTable
                        Dim fc As New ForumController()
                        ForumTable = fc.GetForumView(PortalId, ModuleId, CurrentUserId, UserInfo.IsSuperUser, ForumIds) ' KR - added cache retreival
                        'ds = DataProvider.Instance.UI_ForumView(PortalId, ModuleId, CurrentUserId, UserInfo.IsSuperUser, ForumIds)
                        'ForumTable = ds.Tables(0)
                    End If
                    Dim sCrumb As String = String.Empty
                    Dim sGroupName As String = String.Empty
                    'Dim ForumGroupId As Integer = 0
                    If Not ForumGroupId = -1 Then
                        Dim tmpDR As DataRow = Nothing
                        ForumTable.DefaultView.RowFilter = "ForumGroupId = " & ForumGroupId
                        If ForumTable.DefaultView.ToTable.Rows.Count > 0 Then
                            tmpDR = ForumTable.DefaultView.ToTable.Rows(0)
                        End If
                        If Not tmpDR Is Nothing Then
                            sGroupName = tmpDR("GroupName").ToString
                            sCrumb = "<div class=""afcrumb""><a href=""" & Utilities.NavigateUrl(TabId) & """>[RESX:ForumMain]</a>[RESX:BreadCrumbSep]" & tmpDR("GroupName").ToString & "</div>"
                        End If


                        'dtForums.DefaultView.RowFilter = ""

                    End If
                    If Not ParentForumId = -1 Then
                        'SubsOnly = True
                        Dim tmpDR As DataRow = Nothing
                        Dim sFilter As String = "ForumId = " & ParentForumId & " "

                        ForumTable.DefaultView.RowFilter = sFilter
                        If ForumTable.DefaultView.ToTable.Rows.Count > 0 Then
                            tmpDR = ForumTable.DefaultView.ToTable.Rows(0)
                        End If
                        ForumTable.DefaultView.RowFilter = ""
                        sGroupName = tmpDR("GroupName").ToString

                    End If
                    If MainSettings.UseSkinBreadCrumb And ForumTable.Rows.Count > 0 And SubsOnly = False And Not ForumGroupId = -1 Then
                        Environment.UpdateBreadCrumb(Page.Controls, "<a href=""" & NavigateUrl(TabId, "", ParamKeys.GroupId & "=" & ForumGroupId) & """>" & sGroupName & "</a>")
                        sTemplate = sTemplate.Replace("<div class=""afcrumb"">[FORUMMAINLINK] > [FORUMGROUPLINK]</div>", String.Empty)
                        sTemplate = sTemplate.Replace("[BREADCRUMB]", String.Empty)
                    Else
                        sTemplate = sTemplate.Replace("[BREADCRUMB]", sCrumb)
                    End If

                    Dim dr As DataRow = Nothing
                    Dim iForum As Integer = 1
                    Dim ForumCount As Integer = 0
                    Dim hasForums As Boolean = False
                    Dim rsForums As DataTable = ForumTable.DefaultView.ToTable
                    Dim fi As Forum = Nothing
                    Dim tmpGroupCount As Integer = 0
                    Dim asForumGroupId As Integer = -1
                    Dim social As New Social
                    asForumGroupId = social.GetMasterForumGroup(PortalId, TabId)
                    Dim groupForumsCount As Integer = 0
                    For Each dr In rsForums.Rows

                        'If CBool(dr("CanView")) Or (Not CBool(dr("GroupHidden"))) Then ' And Not CBool(dr("CanView"))) Or UserInfo.IsSuperUser Then
                        If Not (asForumGroupId = CInt(dr("ForumGroupId")) And CBool(dr("GroupHidden")) = True) Then
                            If tmpGroup <> dr("GroupName").ToString Then
                                If tmpGroupCount < Globals.GroupCount Then
                                    ForumTable.DefaultView.RowFilter = "ForumGroupId = " & CInt(dr("ForumGroupId")) & " AND ParentForumId = 0"

                                    ForumCount = ForumTable.DefaultView.Count
                                    ForumTable.DefaultView.RowFilter = ""
                                    If Not sForums = String.Empty Then
                                        sGroupSection = TemplateUtils.ReplaceSubSection(sGroupSection, sForums, "[FORUMS]", "[/FORUMS]")
                                        sForums = String.Empty
                                    End If
                                    Dim GroupId As Integer = CInt(dr("ForumGroupId"))
                                    sGroupSectionTemp = TemplateUtils.GetTemplateSection(sTemplate, "[GROUPSECTION]", "[/GROUPSECTION]")
                                    sGroupSectionTemp = sGroupSectionTemp.Replace("[GROUPNAME]", dr("GroupName").ToString)
                                    sGroupSectionTemp = sGroupSectionTemp.Replace("[FORUMGROUPID]", dr("ForumGroupId").ToString)
                                    sGroupSectionTemp = sGroupSectionTemp.Replace("[GROUPCOLLAPSE]", "<img class=""afarrow"" id=""imgGroup" & GroupId.ToString & """ onclick=""toggleGroup(" & GroupId.ToString & ");"" src=""" & ThemePath & GetImage(GroupId) & """ alt=""[RESX:ToggleGroup]"" />")

                                    'any replacements on the group
                                    Dim sNewGroup As String = "<div id=""group" & GroupId & """ " & GetDisplay(GroupId) & " class=""afgroup"">" & sGroup & "</div>"
                                    sGroupSectionTemp = TemplateUtils.ReplaceSubSection(sGroupSectionTemp, sNewGroup, "[GROUP]", "[/GROUP]")
                                    sGroupSection &= sGroupSectionTemp
                                    tmpGroup = dr("GroupName").ToString
                                    tmpGroupCount += 1
                                    iForum = 1
                                End If

                            End If
                            If iForum <= Globals.ForumCount Then
                                fi = FillForumRow(dr)
                                Dim canView As Boolean = Permissions.HasPerm(fi.Security.View, ForumUser.UserRoles)
                                If canView Or (Not fi.Hidden And Not canView) Then
                                    sForumTemp = TemplateUtils.GetTemplateSection(sTemplate, "[FORUMS]", "[/FORUMS]")
                                    hasForums = True
                                    If fi.ParentForumId = 0 Or SubsOnly Or (SubsOnly = False And fi.ParentForumId > 0 And rsForums.Rows.Count = 1) Then
                                        sForumTemp = ParseForumRow(sForumTemp, fi, iForum, ThemePath, ForumCount)
                                        iForum += 1
                                        sForums &= sForumTemp
                                    End If
                                End If
                            End If
                        End If




                        'End If
                    Next

                    If hasForums = False And SubsOnly Then
                        Return String.Empty
                    Else
                        If Not sForums = String.Empty Then
                            sGroupSection = TemplateUtils.ReplaceSubSection(sGroupSection, sForums, "[FORUMS]", "[/FORUMS]")
                        End If
                        If sTemplate.Contains("[GROUPSECTION]") Then
                            sTemplate = TemplateUtils.ReplaceSubSection(sTemplate, sGroupSection, "[GROUPSECTION]", "[/GROUPSECTION]")
                        Else
                            sTemplate = sGroupSection
                        End If


                    End If
                    sTemplate = TemplateUtils.ReplaceSubSection(sTemplate, String.Empty, "[FORUMS]", "[/FORUMS]")

                End If


                Return sTemplate
            Catch ex As Exception
                DotNetNuke.Services.Exceptions.LogException(ex)
                Return String.Empty
            End Try
        End Function
        Private Function FillForumRow(ByVal dr As DataRow) As Forum
            Dim fi As New Forum
            Try
                With fi
                    .ForumID = CInt(dr("ForumId"))
                    .ForumName = dr("ForumName").ToString
                    .ForumDesc = dr("ForumDesc").ToString
                    .Security.Read = dr("CanRead").ToString
                    .Security.View = dr("CanView").ToString
                    .Security.Subscribe = dr("CanSubscribe").ToString
                    .ParentForumId = CInt(dr("ParentForumId"))


                    .LastPostSubject = dr("LastPostSubject").ToString
                    .LastPostDisplayName = dr("LastPostAuthorName").ToString.Replace("&amp;#", "&#")
                    .LastPostUserID = CInt(dr("LastPostAuthorId"))
                    .LastPostDateTime = CDate(dr("LastPostDate"))

                    .LastPostUserName = .LastPostDisplayName


                    If Not dr("LastRead").ToString = String.Empty Then
                        .LastRead = CDate(dr("LastRead"))
                    End If

                    .ForumGroup = New ForumGroupInfo
                    .ForumGroup.ForumGroupId = Integer.Parse(dr("ForumGroupId").ToString)
                    .ForumGroup.PrefixURL = dr("GroupPrefixURL").ToString
                    .ForumGroupId = Integer.Parse(dr("ForumGroupId").ToString)
                    .TopicUrl = dr("TopicURL").ToString

                    .TopicSubject = dr("LastPostSubject").ToString
                    .TopicId = CInt(dr("LastTopicId"))
                    If Not String.IsNullOrEmpty(dr("AllowRSS").ToString()) Then
                        .AllowRSS = CBool(dr("AllowRSS"))
                    Else
                        .AllowRSS = False
                    End If

                    .TotalTopics = CInt(dr("TotalTopics"))
                    .TotalReplies = CInt(dr("TotalReplies"))
                    .Hidden = CBool(dr("ForumHidden"))
                    .LastReplyId = CInt(dr("LastReplyId"))
                    .LastTopicId = CInt(dr("LastTopicId"))
                    .PrefixURL = dr("PrefixURL").ToString
                    If .LastReplyId = 0 Then
                        .LastPostID = .LastTopicId
                    Else
                        .LastPostID = .LastReplyId
                    End If

                    '.Active = CBool(dr("Active"))
                End With
            Catch ex As Exception
                DotNetNuke.Services.Exceptions.LogException(ex)
            End Try

            Return fi
        End Function
        Private Sub LinkControls(ByVal ctrls As ControlCollection)
            For Each ctrl As Control In ctrls
                If TypeOf (ctrl) Is ForumBase Then
                    DirectCast(ctrl, ForumBase).ModuleConfiguration = Me.ModuleConfiguration

                End If
                If ctrl.Controls.Count > 0 Then
                    LinkControls(ctrl.Controls)
                End If
            Next
        End Sub
        Private Function ParseControls(ByVal Template As String) As String
            Dim sOutput As String = Template
            sOutput = sOutput.Replace("[JUMPTO]", "<asp:placeholder id=""plhQuickJump"" runat=""server"" />")
            If sOutput.Contains("[STATISTICS]") Then
                sOutput = sOutput.Replace("[STATISTICS]", "<am:Stats id=""amStats"" MID=""" & ModuleId & """ PID=""" & PortalId.ToString & """ runat=""server"" />")
            End If
            If sOutput.Contains("[WHOSONLINE]") Then
                If MainSettings.UsersOnlineEnabled Then
                    sOutput = sOutput.Replace("[WHOSONLINE]", "<asp:placeholder id=""plhUsersOnline"" runat=""server"" />")
                Else
                    sOutput = sOutput.Replace("[WHOSONLINE]", String.Empty)
                End If

            End If
            sOutput = sOutput.Replace("[PORTALID]", PortalId.ToString)
            sOutput = sOutput.Replace("[MODULEID]", ModuleId.ToString)
            sOutput = sOutput.Replace("[TABID]", TabId.ToString)
            sOutput = sOutput.Replace("[USERID]", CurrentUserId.ToString)
            Return sOutput
        End Function
        Private Function ParseForumRow(ByVal Template As String, ByVal fi As Forum, ByVal currForumIndex As Integer, ByVal ThemePath As String, ByVal totalForums As Integer) As String


            If Template.Contains("[SUBFORUMS]") And Template.Contains("[/SUBFORUMS]") Then
                Template = GetSubForums(Template, fi.ForumID, ModuleId, TabId, ThemePath)
            Else
                Template = Template.Replace("[SUBFORUMS]", GetSubForums(fi.ForumID, ModuleId, TabId))
            End If
            Dim css() As String = Nothing
            Dim cssmatch As String = String.Empty
            If Template.Contains("[CSS:") Then
                Dim pattern As String = "(\[CSS:.+?\])"
                If Regex.IsMatch(Template, pattern) Then
                    cssmatch = Regex.Match(Template, pattern).Value
                    css = cssmatch.Split(CChar(":")) '0=CSS,1=TopRow, 2=mid rows, 3=lastRow
                End If
            End If
            If Not cssmatch = String.Empty Then
                If currForumIndex = 1 Then
                    Template = Template.Replace(cssmatch, css(1))
                ElseIf currForumIndex > 1 And currForumIndex < totalForums Then
                    Template = Template.Replace(cssmatch, css(2))
                Else
                    Template = Template.Replace(cssmatch, css(3).Replace("]", String.Empty))
                End If
            End If
            With fi

                Dim canView As Boolean = Permissions.HasPerm(.Security.View, ForumUser.UserRoles)
                Dim canSubscribe As Boolean = Permissions.HasPerm(.Security.Subscribe, ForumUser.UserRoles)
                Dim canRead As Boolean = Permissions.HasPerm(.Security.Read, ForumUser.UserRoles)
                Dim sIcon As String = TemplateUtils.ShowIcon(canView, .ForumID, CurrentUserId, .LastPostDateTime, .LastRead, .LastPostID)
                Dim sIconImage As String = "<img alt=""" & .ForumName & """ src=""" & ThemePath & "images/" & sIcon & """ />"
                If Template.Contains("[FORUMICON]") Then
                    Template = Template.Replace("[FORUMICON]", sIconImage)
                ElseIf Template.Contains("[FORUMICONCSS]") Then
                    Dim sFolderCSS As String = "affolder"
                    Select Case sIcon.ToLower
                        Case "folder.png"
                            sFolderCSS = "affolder"
                        Case "folder_new.png"
                            sFolderCSS = "affoldernew"
                        Case "folder_forbidden.png"
                            sFolderCSS = "affolderblock"
                        Case "folder_closed.png"
                            sFolderCSS = "affolderclosed"
                    End Select
                    Template = Template.Replace("[FORUMICONCSS]", "<div class=""" & sFolderCSS & """></div>")
                End If
                Dim ctlUtils As New ControlUtils
                ForumURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, .ForumGroup.PrefixURL, .PrefixURL, .ForumGroupId, .ForumID, -1, String.Empty, -1, -1, String.Empty, 1, SocialGroupId)

                'ForumURL = GetForumLink(.ForumID, TabId, canView, MainSettings.UseShortUrls, .PrefixURL)
                Template = Template.Replace("[FORUMNAME]", GetForumLink(.ForumName, .ForumID, TabId, canView, ForumURL))
                Template = Template.Replace("[FORUMNAMENOLINK]", .ForumName)
                Template = Template.Replace("[FORUMID]", .ForumID.ToString)
                If Template.Contains("[RSSLINK]") Then
                    If .AllowRSS And canRead Then
                        Dim Url As String
                        Url = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/DesktopModules/ActiveForums/feeds.aspx?portalid=" & PortalId & "&forumid=" & .ForumID & "&tabid=" & TabId & "&moduleid=" & ModuleId
                        Template = Template.Replace("[RSSLINK]", "<a href=""" & Url & """ target=""_blank""><img src=""" & ThemePath & "images/rss.png"" border=""0"" alt=""[RESX:RSS]"" /></a>")
                    Else
                        Template = Template.Replace("[RSSLINK]", "<img src=""" & ThemePath & "images/rss_disabled.png"" border=""0"" alt=""[RESX:RSSDisabled]"" />")
                    End If
                End If

                If Template.Contains("[AF:CONTROL:TOGGLESUBSCRIBE]") Then
                    If canSubscribe Then
                        Dim IsSubscribed As Boolean = Subscriptions.IsSubscribed(PortalId, ModuleId, .ForumID, 0, SubscriptionTypes.Instant, CurrentUserId)
                        Dim sAlt As String = "[RESX:ForumSubscribe:" & IsSubscribed.ToString.ToUpper & "]"
                        Dim sImg As String = ThemePath & "images/email_unchecked.png"
                        If IsSubscribed Then
                            sImg = ThemePath & "images/email_checked.png"
                        End If
                        Dim subControl As New Controls.ToggleSubscribe(0, .ForumID, -1)
                        subControl.Checked = IsSubscribed
                        subControl.DisplayMode = 1
                        subControl.UserId = CurrentUserId
                        subControl.ImageURL = sImg
                        subControl.Text = "[RESX:ForumSubscribe:" & IsSubscribed.ToString.ToUpper & "]"
                        Dim subOption As String = subControl.Render()

                        'Template = Template.Replace("[AF:CONTROL:TOGGLESUBSCRIBE]", "<a href=""javascript:af_toggleSubscribe(" & .ForumID & ",'" & PortalId & "|" & ModuleId & "|" & .ForumID & "|" & CurrentUserId & "');""><img id=""toggleSub" & .ForumID & """ src=""" & sImg & """ border=""0"" alt=""" & sAlt & """ /></a>")
                        Template = Template.Replace("[AF:CONTROL:TOGGLESUBSCRIBE]", subOption)
                    Else
                        Template = Template.Replace("[AF:CONTROL:TOGGLESUBSCRIBE]", "<img src=""" & ThemePath & "email_disabled.png"" border=""0"" alt=""[RESX:ForumSubscribe:Disabled]"" />")
                    End If
                End If

                If canRead Then
                    Template = Template.Replace("[AF:CONTROL:ADDFAVORITE]", "<a href=""javascript:afAddBookmark('" & .ForumName & "','" & ForumURL & "');""><img src=""" & ThemePath & "images/favorites16_add.png"" border=""0"" alt=""[RESX:AddToFavorites]"" /></a>")
                Else
                    Template = Template.Replace("[AF:CONTROL:ADDFAVORITE]", String.Empty)
                End If
                If Template.Contains("[AF:CONTROL:ADDTHIS") Then
                    Template = TemplateUtils.ParseSpecial(Template, SpecialTokenTypes.AddThis, ForumURL, .ForumName, canRead, MainSettings.AddThisAccount)
                End If
                Template = Template.Replace("[FORUMDESCRIPTION]", .ForumDesc)
                Template = Template.Replace("[TOTALTOPICS]", .TotalTopics.ToString)
                Template = Template.Replace("[TOTALREPLIES]", .TotalReplies.ToString)
                'Last Post Section
                Dim intLength As Integer = 0
                If InStr(Template, "[LASTPOSTSUBJECT:") > 0 Then
                    Dim inStart As Integer = InStr(Template, "[LASTPOSTSUBJECT:") + 17
                    Dim inEnd As Integer = InStr(inStart, Template, "]")
                    Dim sLength As String = Template.Substring(inStart - 1, inEnd - inStart)
                    intLength = CType(sLength, Integer)
                End If
                Dim ReplaceTag As String = "[LASTPOSTSUBJECT:" & intLength.ToString & "]"
                If .LastPostID = 0 Then
                    Template = Template.Replace("[RESX:BY]", String.Empty)
                    Template = Template.Replace("[DISPLAYNAME]", String.Empty)
                    Template = Template.Replace("[LASTPOSTDATE]", String.Empty)
                    Template = Template.Replace(ReplaceTag, String.Empty)
                    'Template = TemplateUtils.ParseUserDetails(PortalId, -1, Template, String.Empty)
                Else
                    If canView Then
                        If .LastPostUserID <= 0 Then
                            'Template = Template.Replace("[RESX:BY]", String.Empty)
                            Template = Template.Replace("[DISPLAYNAME]", .LastPostDisplayName)
                            'Template = TemplateUtils.ParseUserDetails(PortalId, -1, Template, "FG")
                        Else
                            Dim isMod As Boolean = False
                            If CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.ForumMod Or CurrentUserType = CurrentUserTypes.SuperUser Then
                                isMod = True
                            End If
                            Template = Template.Replace("[DISPLAYNAME]", UserProfiles.GetDisplayName(ModuleId, MainSettings.ProfileVisibility, isMod, .LastPostUserID, MainSettings.UserNameDisplay, .LastPostUserName, .LastPostFirstName, .LastPostLastName, .LastPostDisplayName))
                            'Template = TemplateUtils.ParseUserDetails(PortalId, .LastPostUserID, Template, "FG")
                        End If
                        Dim dtLastPostDate As Date = .LastPostDateTime
                        Template = Template.Replace("[LASTPOSTDATE]", Utilities.GetDate(dtLastPostDate, ModuleId, TimeZoneOffset))
                        Dim Subject As String = .LastPostSubject
                        If Subject = "" Then
                            Subject = GetSharedResource("[RESX:SubjectPrefix]") & " " & .TopicSubject
                        End If
                        If Not Subject = String.Empty Then
                            Dim sDots As String = ""
                            If Subject.Length > intLength Then
                                sDots = "..."
                            End If

                            Template = Template.Replace(ReplaceTag, GetLastPostSubject(.LastPostID, .TopicId, .ForumID, TabId, Subject, intLength, MainSettings.PageSize, fi))
                        Else
                            Template = Template.Replace("[RESX:BY]", String.Empty)
                            Template = Template.Replace(ReplaceTag, String.Empty)
                        End If
                    Else
                        Template = Template.Replace("[DISPLAYNAME]", String.Empty)
                        Template = Template.Replace("[LASTPOSTDATE]", String.Empty)
                        Template = Template.Replace("[RESX:BY]", String.Empty)
                        Template = Template.Replace(ReplaceTag, String.Empty)
                    End If

                End If
            End With

            Return Template


        End Function
    
#End Region
#Region "Private Methods - Helpers"
        Private Function GetForumLink(ByVal ForumId As Integer, ByVal TabId As Integer, ByVal CanView As Boolean, ByVal Url As String) As String
            Return GetForumLink(String.Empty, ForumId, TabId, CanView, Url)
        End Function
        Private Function GetForumLink(ByVal Name As String, ByVal ForumId As Integer, ByVal TabId As Integer, ByVal CanView As Boolean, ByVal Url As String) As String
            Dim sOut As String
            sOut = Name
            'Dim sTopicURL As String = String.Empty

            'Dim Params() As String = {ParamKeys.ForumId & "=" & ForumId}
            'Dim sURL As String = String.Empty
            'If Not MainSettings.URLRewriteEnabled Or String.IsNullOrEmpty(PrefixURL) Then
            '    sURL = Utilities.NavigateUrl(TabId, "", Params)
            'Else
            '    sURL = "/"
            '    If Not String.IsNullOrEmpty(MainSettings.PrefixURLBase) Then
            '        sURL &= MainSettings.PrefixURLBase & "/"
            '    End If
            '    sURL &= PrefixURL & "/"
            'End If

            If CanView And Not Name = String.Empty Then
                sOut = "<a href=""" & Url & """>" & Name & "</a>"

            ElseIf CanView And Name = String.Empty Then
                Return Url
            Else
                sOut = Name
            End If
            Return sOut
        End Function
        Private Function GetImage(ByVal GroupID As Integer) As String
            If Not Request.Cookies(GroupID & "Show") Is Nothing Then
                If CType(Request.Cookies(GroupID & "Show").Value, Boolean) = True Then
                    Return "images/arrows_down.png"
                Else
                    Return "images/arrows_left.png"
                End If
            Else
                Return "images/arrows_down.png"
            End If
        End Function
        Private Function GetDisplay(ByVal GroupID As Integer) As String
            Dim bolShow As Boolean = True
            If Not Request.Cookies(GroupID & "S") Is Nothing Then
                Dim sShow As String = CType(Request.Cookies(GroupID & "S").Value, String)
                If sShow = "F" Then
                    bolShow = False
                Else
                    bolShow = True
                End If
            End If
            If bolShow = True Then
                Return " style=""clear:both;"""
            Else
                Return " style=""clear:both;display:none;"""
            End If

        End Function
        Private Function GetLastPostSubject(ByVal LastPostID As Integer, ByVal ParentPostID As Integer, ByVal ForumID As Integer, ByVal TabID As Integer, ByVal Subject As String, ByVal Length As Integer, ByVal PageSize As Integer, ByVal fi As Forum) As String
            'TODO: Verify that this will still jump to topics on page 2
            Dim sb As New Text.StringBuilder
            Dim PostId As Integer = LastPostID
            Subject = Utilities.StripHTMLTag(Subject)
            Subject = Replace(Subject, "[", "&#91")
            Subject = Replace(Subject, "]", "&#93")
            If Subject.Length > Length And Length > 0 Then
                Subject = Subject.Substring(0, Length) & "..."
            End If
            If Not LastPostID = 0 Then
                Dim sTopicURL As String = String.Empty
                Dim ctlUtils As New ControlUtils
                sTopicURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, fi.ForumGroup.PrefixURL, fi.PrefixURL, fi.ForumGroupId, ForumID, ParentPostID, fi.TopicUrl, -1, -1, String.Empty, 1, SocialGroupId)

                Dim sURL As String = String.Empty
                If ParentPostID = 0 Or LastPostID = ParentPostID Then
                    sURL = sTopicURL
                    'If UseShortUrls Then
                    '    sURL = Utilities.NavigateUrl(TabID, "", New String() {ParamKeys.TopicId & "=" & PostId})
                    'Else
                    '    sURL = Utilities.NavigateUrl(TabID, "", New String() {ParamKeys.ForumId & "=" & ForumID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & PostId})
                    'End If
                Else
                    If sTopicURL.EndsWith("/") Then
                        sURL = sTopicURL & "?" & ParamKeys.ContentJumpId & "=" & PostId
                    Else
                        sURL = Utilities.NavigateUrl(TabID, "", New String() {ParamKeys.TopicId & "=" & ParentPostID, ParamKeys.ContentJumpId & "=" & PostId})
                    End If



                End If
                sb.Append("<a href=""" & sURL & """>" & DotNetNuke.Modules.ActiveForums.Utilities.HTMLEncode(Subject) & "</a>")
            End If
            Return sb.ToString
        End Function
        Private Function GetSubForums(ByVal ForumId As Integer, ByVal ModuleId As Integer, ByVal TabId As Integer) As String
            Return GetSubForums(String.Empty, ForumId, ModuleId, TabId, String.Empty)
        End Function
        Private Function GetSubForums(ByVal Template As String, ByVal ForumId As Integer, ByVal ModuleId As Integer, ByVal TabId As Integer, ByVal ThemePath As String) As String
            Dim i As Integer = 0
            Dim dr As DataRow = Nothing
            Dim sFilter As String = "ParentForumId = " & ForumId
            'If Not ForumIds = String.Empty Then
            '    sFilter = String.Empty
            '    For Each f As String In ForumIds.Split(CChar(";"))
            '        If Not f = String.Empty Then
            '            If Not sFilter = String.Empty Then
            '                sFilter = sFilter & " OR "
            '            End If
            '            sFilter &= " (ParentForumId = " & ForumId & " AND ForumId = " & f & ") "
            '        End If
            '    Next
            'End If
            ForumTable.DefaultView.RowFilter = sFilter
            Dim rows As Integer = ForumTable.DefaultView.Count
            If Template = String.Empty Then
                Dim sb As New StringBuilder
                Dim SubForum As String = String.Empty
                For Each dr In ForumTable.DefaultView.ToTable.Rows
                    If CInt(dr("ParentForumId")) = ForumId Then
                        Dim canView As Boolean = Permissions.HasPerm(dr("CanView").ToString, ForumUser.UserRoles)
                        SubForum = GetForumName(ModuleId, canView, CBool(dr("ForumHidden")), TabId, CInt(dr("ForumGroupId")), CInt(dr("ForumId")), dr("ForumName").ToString, MainSettings.UseShortUrls)
                        If Not SubForum = String.Empty Then
                            sb.Append(SubForum)
                            If i < rows - 1 Then
                                sb.Append(", ")
                            End If
                            i += 1
                        End If

                    End If
                Next
                Dim subs As String = String.Empty
                If sb.Length > 0 Then
                    sb.Insert(0, "<br />[RESX:SubForums] ")
                    subs = sb.ToString
                    subs = subs.Trim
                    If subs.IndexOf(",", subs.Length - 1) > 0 Then
                        subs = subs.Substring(0, subs.LastIndexOf(","))
                    End If
                End If
                ForumTable.DefaultView.RowFilter = ""
                Return subs
            Else
                Dim subs As String = String.Empty
                For Each dr In ForumTable.DefaultView.ToTable.Rows
                    i += 1
                    Dim tmpSubs As String = TemplateUtils.GetTemplateSection(Template, "[SUBFORUMS]", "[/SUBFORUMS]")
                    Dim fi As Forum = FillForumRow(dr)
                    Dim canView As Boolean = Permissions.HasPerm(dr("CanView").ToString, ForumUser.UserRoles)
                    If canView Or (Not fi.Hidden And Not canView) Or UserInfo.IsSuperUser Then
                        Dim sIcon As String = TemplateUtils.ShowIcon(canView, fi.ForumID, CurrentUserId, fi.LastPostDateTime, fi.LastRead, fi.LastPostID)
                        Dim sIconImage As String = "<img alt=""" & fi.ForumName & """ src=""" & ThemePath & "images/" & sIcon & """ />"
                        tmpSubs = tmpSubs.Replace("[FORUMICONSM]", sIconImage.Replace("folder", "folder16"))
                        tmpSubs = ParseForumRow(tmpSubs, fi, i, ThemePath, ForumTable.DefaultView.ToTable.Rows.Count)
                    Else
                        tmpSubs = String.Empty
                    End If
                    subs &= tmpSubs
                Next
                ForumTable.DefaultView.RowFilter = ""
                Template = TemplateUtils.ReplaceSubSection(Template, subs, "[SUBFORUMS]", "[/SUBFORUMS]")
                Return Template
            End If

        End Function
        Private Function GetForumName(ByVal ModuleID As Integer, ByVal CanView As Boolean, ByVal Hidden As Boolean, ByVal TabID As Integer, ByVal ForumGroupID As Integer, ByVal ForumID As Integer, ByVal Name As String, ByVal UseShortUrls As Boolean) As String
            Dim sOut As String
            sOut = Name
            Dim Params() As String = {ParamKeys.ViewType & "=" & Views.Topics, ParamKeys.ForumId & "=" & ForumID}
            If UseShortUrls Then
                Params = New String() {ParamKeys.ForumId & "=" & ForumID}
            End If
            If CanView Then
                sOut = "<a href=""" & Utilities.NavigateUrl(TabID, "", Params) & """>" & Name & "</a>"
            ElseIf CanView = False And Hidden = True Then
                sOut = String.Empty
            Else
                sOut = Name
            End If
            Return sOut
        End Function
#End Region

    End Class

End Namespace